package com.snail.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceAutoConfig {

    private final DynamicDataSourceProperties properties;

    public DynamicDataSourceAutoConfig(DynamicDataSourceProperties properties) {
        this.properties = properties;
    }

    //手动创建数据源提供者
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return () -> {
            Map<String, DataSource> dataSources = new HashMap<>();
            // 遍历配置中的数据源，创建并添加到Map
            properties.getDatasource().forEach((name, config) -> {
                HikariConfig hikariConfig = new HikariConfig();
                hikariConfig.setJdbcUrl(config.getUrl());
                hikariConfig.setUsername(config.getUsername());
                hikariConfig.setPassword(config.getPassword());
                hikariConfig.setDriverClassName(config.getDriverClassName());
                hikariConfig.setMaximumPoolSize(10);
                hikariConfig.setMinimumIdle(2);
                dataSources.put(name, new HikariDataSource(hikariConfig));
            });
            return dataSources;
        };
    }

    //手动创建动态数据源Bean
    @Bean("dynamicDataSource")
    @Primary
    public DataSource dynamicDataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        // 逐个添加数据源
        dynamicDataSourceProvider.loadDataSources().forEach(dataSource::addDataSource);
        // 设置默认数据源
        dataSource.setPrimary(properties.getPrimary());
        return dataSource;
    }
}
